package org.wu.framework.authorization.web.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.wu.framework.authorization.annotation.NoAuthorizationRequired;
import org.wu.framework.authorization.annotation.RequiredAuthorization;
import org.wu.framework.authorization.config.pro.AuthorizationProperties;
import org.wu.framework.authorization.model.Permission;
import org.wu.framework.authorization.model.UserDetails;

import java.util.List;


/**
 * 控制角色
 */

@Slf4j
public class RequirePermissionInterceptorAbstract extends AbstractAuthorizationHandlerInterceptorAbstract {


    private AntPathMatcher matcher = new AntPathMatcher();

    public RequirePermissionInterceptorAbstract(AuthorizationProperties authorizationProperties) {
        super(authorizationProperties);
        ;
    }


    /**
     * 是否有权限
     */
    @Override
    public boolean doHasPermission(HttpServletRequest request, HandlerMethod handler) {
        // 获取方法上的注解
        if (handler.getBean().getClass().getAnnotation(RequiredAuthorization.class) == null
                || handler.getMethod().getAnnotation(RequiredAuthorization.class) == null) {
            return true;
        }
        String requestURI = request.getRequestURI();
        String requestMethod = request.getMethod();

        UserDetails userDetails = (UserDetails) request.getAttribute(REQUEST_TOKEN_USER_ATTR_KEY);
        List<? extends Permission> permissionList = userDetails.getPermissionList();
        // 验证权限
        if (permissionList
                .stream()
                .anyMatch(permission -> {
                    String url = permission.getUrl();
                    String method = permission.getMethod();
                    return matcher.match(url, requestURI) && matcher.match(method, requestMethod);
                })) {
            // 有权限，授权通过
            return true;
        } else {
            // 授权失败
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
